import pkgutil
import importlib
import os


def iter_all_modules(package, prefix='', prefix_filter=''):
    """
    获取某package下所有module列表(深度遍历)
    :param package:目录或者包
    :param prefix,
    :param prefix_filter:过滤字段,如handler,service,model等
    """
    if type(package) is not str:
        path, prefix = package.__path__[0], package.__name__ + '.'
    else:
        path = package
    for _, name, is_package in pkgutil.iter_modules([path]):
        # 如果是一个包，那么进行递归
        if is_package:
            for m in iter_all_modules(os.path.join(path, name),
                                      prefix=prefix + name + '.',
                                      prefix_filter=prefix_filter):
                yield m
        else:
            if name.startswith(prefix_filter):
                yield importlib.import_module(prefix + name)
